﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.Operation;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.ConvertElement.ServiceArgs;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace Kingdee.SR.Plugin
{
    [Description("打开其他单据")]
    [HotUpdate]
    public class OpenOtherFormPlugIn : AbstractBillPlugIn
    {
        //public override void ButtonClick(ButtonClickEventArgs e)
        //{
        //    base.ButtonClick(e);
        //    if (e.Key.EqualsIgnoreCase("F_WSWB_Button"))
        //    {
        //        BillShowParameter showParam = new BillShowParameter();
        //        showParam.FormId = "SAL_SaleOrder";
        //        showParam.Status = OperationStatus.EDIT;
        //        showParam.PKey = "100001";

        //        this.View.ShowForm(showParam);
        //    }
        //}

        public override void BarItemClick(BarItemClickEventArgs e)

        {

            base.BarItemClick(e);

            if (e.BarItemKey.EqualsIgnoreCase("WOIN_tbButton1"))

            {
                string FormTitle = this.View.Model.DataObject["Id"].ToString();

                var rows = DBUtils.ExecuteDynamicObject(this.Context, string.Format("select * from CAiGou where FID={0}", FormTitle));

                foreach (var row in rows)

                {

                    IConvertService service = Kingdee.BOS.App.ServiceHelper.GetService<IConvertService>();

                    string convertRuleld = "SCP_InStockTOPayableMap";

                    var rule = ConvertServiceHelper.GetConvertRule(this.Context, convertRuleld).Rule;

                    List<ListSelectedRow> selectedRows = new List<ListSelectedRow>();

                    string sourceFormId = "SCP_InStock";//发起下推的单据标识



                    string primaryKeyValue = row["FID"].ToString();//单据头内码



                    string entryPrimaryKeyValue = row["FENTRYID"].ToString();//下推的单据体内码



                    int rowKey = 0;//暂时没用上，给个0



                    ListSelectedRow sr = new ListSelectedRow(primaryKeyValue, entryPrimaryKeyValue, rowKey,



                    sourceFormId);

                    selectedRows.Add(sr);

                    PushArgs pushargs = new PushArgs(rule, selectedRows.ToArray());//下推入口参数



                    OperateOption option = OperateOption.Create();//选项参数



                    option.SetVariableValue("customizeParam", "1");//注册自定义参数键值对


                    ConvertOperationResult result = ConvertServiceHelper.Push(this.Context, pushargs, option);

                    // 获取生成的目标单据数据包，此处获取是为了拿到内码，做到像标准下推那样的弹出下游单据的功能

                    DynamicObject[] objs = (from p in result.TargetDataEntities select p.DataEntity).ToArray();

                    // 读取目标单据元数据

                    var targetBillMeta = MetaDataServiceHelper.Load(this.Context, "AP_PAYABLE") as FormMetadata;

                    OperateOption saveOption = OperateOption.Create();//AP_PAYABLE目标单据标识

                    // 忽略全部需要交互性质的提示，直接保存；

                    saveOption.SetIgnoreWarning(true); // 提交数据库保存，并获取暂存结果

                    var saveResult = BusinessDataServiceHelper.Draft(this.Context, targetBillMeta.BusinessInfo, objs, saveOption);

                    var dy = saveResult.SuccessDataEnity.ToList();

                    var FID = dy[0]["Id"].ToString();

                    if (result.IsSuccess == true)

                    {

                        //弹出下游单据

                        string pageId = Guid.NewGuid().ToString();

                        BillShowParameter showParameter = new BillShowParameter();

                        showParameter.FormId = "AP_PAYABLE";

                        showParameter.OpenStyle.ShowType = ShowType.Floating;

                        showParameter.PageId = pageId;

                        showParameter.Status = OperationStatus.EDIT;

                        showParameter.PKey = FID;

                        this.View.ShowForm(showParameter);

                    }

                    else

                    {



                        string msg = $"失败信息{result.IsShowMessage},失败内容{result.ValidationErrors}";

                        throw new Exception(msg);

                    }

                }

            }

        }

    }
}
